package csc.daonjpa.java.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import csc.daonjpa.java.dao.InboxDAO;
import csc.daonjpa.java.domain.Inbox;

@Controller
@RequestMapping(value = "/checkInbox")
public class InboxController {

	@Autowired
	private InboxDAO inboxDAO;
	
	@RequestMapping
	public String goInbox(Model model){
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		String loginId = auth.getName();
		List<Inbox> inboxsSourcce = inboxDAO.getInboxsSource(loginId);
		model.addAttribute("inboxsSource", inboxsSourcce);
		List<Inbox> inboxsTarget = inboxDAO.getInboxsTarget(loginId);
		model.addAttribute("inboxsTarget", inboxsTarget);
		return "inbox";
	}

	@RequestMapping(value = "/ajax", method = RequestMethod.GET)
	@ResponseBody
	public int checkInboxAjax() {
		Authentication auth = SecurityContextHolder.getContext()
				.getAuthentication();
		if (auth == null) {
			return 0;
		} else {
			String loginId = auth.getName();
			int number = inboxDAO.numberMessageNotRead(loginId);
			return number;
		}
	}
	
	@RequestMapping(value="/chagestatus/{id}")
	public String chageStatus(@PathVariable("id") String id){
		Inbox inbox = inboxDAO.getInbox(id);
		inbox.setIsRead("Readed");
		inboxDAO.updateInbox(inbox);
		return "redirect:/checkInbox";
	}
}
